package com.jintian.smart.kernel.common.orm;

import com.jintian.smart.kernel.core.domain.PageQuery;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.io.IOException;

/**
 *
 */
public class PageRequestArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return PageQuery.class.equals(parameter.getParameterType());
    }

    /**
     * page 参数解析
     *
     * @param parameter     MethodParameter
     * @param mavContainer  ModelAndViewContainer
     * @param request       NativeWebRequest
     * @param binderFactory WebDataBinderFactory
     * @return 检查后新的page对象
     */
    @Override
    public Object resolveArgument(@NonNull MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest request, WebDataBinderFactory binderFactory) {
        // Class paramObjClass = parameter.getParameterType();
        // String json = getRequestBody(request);
        // Object paramObj = paramObjClass.newInstance();
        // Object object = JSONObject.parseObject(json, paramObjClass);
        // return object != null ? object : paramObj;
        // request.get
        return null;
    }

    private String getRequestBody(NativeWebRequest webRequest) {
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String jsonBody = (String) webRequest.getAttribute("params", NativeWebRequest.SCOPE_REQUEST);
        if (jsonBody == null) {
            try {
                jsonBody = IOUtils.toString(servletRequest.getInputStream());
                webRequest.setAttribute("params", jsonBody, NativeWebRequest.SCOPE_REQUEST);
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            }
        }

        return jsonBody;
    }
}
